Step 9: Path Parameter

Let's create a route to receive a specific bookmark given its ID.

HTTP MethodGET
API Endpoint/bookmarks/:id
Request Path Parameterid
Request Query Parameter
Request Body
Response BodyJSON object (bookmark)
Response Status200

Notice the API endpoint; to retrieve an item from a collection, it is common to use an endpoint /api/collection/:id where id is the ID of the resource you are searching for.

Update src/routes/bookmarks.js as follows:

router.get("/bookmarks/:id", (req, res) => {
  const { id } = req.params;
  const bookmark = bookmarkDao.read(id);
  res.json({
    status: 200,
    message: `Successfully retrieved the following bookmark!`,
    data: bookmark,
  });
});

Notice how the path contains :id and how I have used the req.params object to get the path parameter.

If you want to identify a resource, you should use the "path parameter." But if you want to sort or filter items, then you should use “query parameter” (will be discussed later).

Save the code and commit the changes. Then, test this endpoint in Postman.

Since we don’t have a persistence mechanism yet, you must create a bookmark before trying to get it given its ID.

Untitled

Notice how I provided the ID in the request in Postman. It closely follows the pattern we present path parameters in Express.